import os
import socket
from  ftplib import FTP
from smb.SMBConnection import *
import configparser
import json
import re
import subprocess
import requests

def IsOpen(ip,port):
    port_d = {'21':"ftp",'53':"DNS",'80':"HTTP",'139':"samba",'443':"https",'445':"samba",'20443':'API',"SSH":"",'3306':"msyql"}
    s = socket.socket()
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        if int(port)==20443:
            very = check_api(ip,port)
            if very:
                print("%6s .......... OK" % port_d[port])
            else:
                print("%6s .......... Fail" % port_d[port])

        print("%6s .......... OK" % port_d[port])
        return True
    except:
        print("%6s .......... Fail" % port_d[port])
        return False
ports = ['21','53','80','139','443','445','20443','3306']

def check_port(ip, ports):
    for i in range(len(ports)):
        IsOpen(ip,ports[i])

ip = '127.0.0.1'
# check_port(ip,ports)   检测端口

def ftpmain(ip,port,username,passwd):
    try:
        ftp = FTP()
        ftp.connect(ip,port)
        ftp.login(username,passwd)
        print(ftp.getwelcome())
    except:
        print('FTP 用户或密码错误')

# ftpmain(ip,21,'root','234')

  #登录
host = ip
username = ""
password = ""
#conn = SMBConnection(username,password,"","",use_ntlm_v2 = True)
#result = conn.connect(host, 445)
print("登录成功")
def smb_con():
    hostname = socket.gethostname()
    local_host = (hostname)
    try:
        conn = SMBConnection('anoymous','','any','',use_ntlm_v2 = True)
        conn.connect('192.168.50.58')
    except Exception as e:
        print(e)
    return conn

def smb_upload(conn):
    #upload
    localFile = open("smb_test.dat","rb")
    conn.storeFile("test.txt","C:/Users/admin/Desktop/img",localFile)
    localFile.close()
    print("上传成功")


def smb_down_load(conn):
    localFile = open("d:/smb_test2.dat", "wb") # "/de/dd/**.txt"
    conn.retrieveFile("smb_test.dat","/test.txt",localFile)
    localFile.close()
    print("下载成功")


def check_file():
    pass

def get_conf():
    cf = configparser.ConfigParser()
    cf.read(os.getcwd()+"/config.conf")
    print(cf.sections()) # 返回列表
 #   cf.options(section="")

def check_ssh():
    pass

def get_dns_ip():

   # output = subprocess.Popen(["ipconfig","/all"], stdout=subprocess.PIPE).communicate()[0].decode("GBK")
   # print(output)
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.connect(('8.8.8.8',80))
    ip = s.getsockname()[0]
    baseinfo = os.popen('ipconfig/all')
    tempstream = baseinfo._stream
    infostrs = tempstream.buffer.read().decode(encoding='gbk')
    infolists = infostrs.splitlines()
    validinfolist = []
    for index, value in enumerate(infolists):
        if ip in value:
            validinfolist = infolists[index: index+11]
    # print(validinfolist)
    pattern = re.compile(r'\d+.\d+.\d+.\d+')
    dns_ip = ''
    dns_des= ''
    for info in validinfolist:
        if 'DHCP 服务器'in info or 'DHCP Server' in info:
            dns_ip = re.findall(pattern,info)
        if '默认网关' in info:
            dns_des = re.findall(pattern,info)
    return dns_ip

def check_api(dns_ip,port):
    s = requests.get('http://'+ dns_ip + port)
    # print(s.status_code)
    if s.status_code==200:
        return True
    else:
        return False

# check dns_ip
def get_conf_dic(dns_ip,ports):
    with open(os.getcwd()+"/config.conf") as f:
        conf_file = f.read()
        ip_list = re.findall('ip":"(.*?)",',conf_file)
        ip_next_list = re.findall('"next_server":"(.*?)",',conf_file)
        ftp_username = re.findall('"ftp":{"username":"(.*?)",',conf_file)
        ftp_password = re.findall('"password":"(.*?)",',conf_file)
        #print(ip_list)
        #print(ip_next_list)
        f.close()
    if dns_ip in ip_list or True:
        print('#' * 20)
        print("[controller: %s]" % dns_ip)

        check_port('127.0.0.1',ports)
        conn = ftpmain(dns_ip,21,ftp_username,ftp_password)
       # upload(conn)
       # down_load(conn)


    else:
        print("没有找到被控节点,dhcp服务器为未知服务器 请检查网络中是否存在多个dhcp服务器!")



#dns_ip = get_dns_ip()
#get_conf_dic(dns_ip,ports)

#check_api('127.0.0.1','80')

conn = smb_con()
smb_upload(conn)
smb_down_load(conn)



